package com.iamdigger.queldorei.monitor.exe;

import com.iamdigger.queldorei.client.RpcClient;
import com.iamdigger.queldorei.common.bean.RpcRequest;
import com.iamdigger.queldorei.common.bean.RpcResponse;
import com.iamdigger.queldorei.common.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;
import java.util.UUID;

/**
 * Remote invoker task
 * Created by Sam Tsai on 2016/4/8.
 */
public class RemoteInvokerTask extends MonitorTask{

    private static final Logger logger = LoggerFactory.getLogger(RemoteInvokerTask.class);
    RemoteInvokerParam rip;

    public RemoteInvokerTask(RemoteInvokerParam rip) {
        this.rip = rip;
    }

    @Override
    public void run() {
        try {
            // 从 RPC 服务地址中解析主机名与端口号
            String[] array = StringUtil.split(rip.serviceAddress, ":");
            String host = array[0];
            int port = Integer.parseInt(array[1]);
            // 创建 RPC 客户端对象并发送 RPC 请求
            RpcClient client = new RpcClient(host, port);
            long time = System.currentTimeMillis();
            RpcResponse response = client.send(rip.assembleRpcRequest());
            logger.debug("monitor {} costs time: {}ms", rip.serviceAddress, System.currentTimeMillis() - time);

            if (response == null || response.hasException()) {
                // 处理服务机器不通的异常情况
                logger.error("!!!!!!!!!!!!!!!Service host {} is down.!!!!!!!!!!!!!!!", rip.serviceAddress);
            }
        } catch (Exception ignore) {}
    }

    static class RemoteInvokerParam {
        String serviceAddress;
        Method method;
        Class interfaceClazz;
        Object[] args;

        RemoteInvokerParam(Class<?> interfaceClazz, Method method, Object[] args, String serviceAddress) {
            this.serviceAddress = serviceAddress;
            this.interfaceClazz = interfaceClazz;
            this.args = args;
            this.method = method;
        }

        RpcRequest assembleRpcRequest() {
            RpcRequest request = new RpcRequest();
            request.setRequestId(UUID.randomUUID().toString());
            request.setInterfaceName(interfaceClazz.getName());
            request.setServiceVersion("");
            request.setMethodName(method.getName());
            request.setParameterTypes(method.getParameterTypes());
            request.setParameters(args);
            return request;
        }
    }
}
